package com.example.shop.modules.other.service.impl;

import com.example.shop.modules.other.service.ICoreService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class CoreServiceImpl implements ICoreService {

    @Override
    public Map<String, Object> createCore(String text, Integer width, Integer height) throws WriterException, IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        text=new String(text.getBytes("UTF-8"),"ISO-8859-1");//如果不想更改源码，则将字符串转换成ISO-8859-1编码
        if(width==null){
            width = 300;
        }
        if(height==null){
            height = 300;
        }
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        byte[] pngData = pngOutputStream.toByteArray();
        map.put("data:image/png;base64", pngData);
        return map;
    }
}
